package com.itrident.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author cxx
 * @create 2020-11-29 17:58
 **/
public class StringUtil {

    public static String humpConvert(String text){
        Pattern pattern = Pattern.compile ("^[^_]*[a-zA-Z_]+[^_]*$");
        if (!pattern.matcher (text).matches ()) {
            return text;
        }
        String allLowRegex = "[a-z]+";
        //全为小写则都改为大写
        if (Pattern.matches (allLowRegex,text)) {
            return text.toUpperCase ();
        }
        String allUpperRegex = "[A-Z]+";
        if (Pattern.matches (allUpperRegex,text)) {
            return text.toLowerCase ();
        }

        String allLetter = "[a-zA-Z]+";
        char[] chars = text.toCharArray ();
        List<Character> newChars = new ArrayList<> (chars.length);
        if (Pattern.matches (allLetter,text)) {
            for (int i = 0; i < chars.length; i++) {
                if(i == 0){
                    addLowChar (chars[0], newChars);
                }else{
                    if(!isUpper (chars[i-1]) && isUpper (chars[i])){
                        newChars.add ('_');
                    }
                    addLowChar (chars[i], newChars);
                }
            }
        }else{
            for (int i = 0; i < chars.length; i++) {
                if (chars[i] != '_') {
                    addLowChar (chars[i], newChars);
                }else{
                    i++;
                    addUpperChar (chars[i], newChars);
                }

            }
        }
        return newChars.stream()
                .map(String::valueOf)
                .collect(Collectors.joining());
    }

    private static void addUpperChar(char aChar, List<Character> newChars) {
        if (isUpper (aChar)){
            newChars.add (aChar);
        }else{
            newChars.add ((char)(aChar - 32));
        }
    }

    private static void addLowChar(char aChar, List<Character> newChars) {
        if (isUpper (aChar)){
            newChars.add ((char)(aChar + 32));
        }else{
            newChars.add (aChar);
        }
    }

    private static boolean isUpper(char c){
        int cl = (int)c;
        if(cl >= 65 && cl <= 90){
            return true;
        }
        return false;
    }

    public static boolean isEmpty(String str) {
        return str == null || "".equals (str);
    }
}
